//
//  HomeViewController.swift
//  LEOweibo
//
//  Created by zz on 16/2/21.
//  Copyright © 2016年 zz. All rights reserved.
//

import UIKit
import YYModel
import AFNetworking
let statusID :String = "HomeViewStatusCell"
let tipID: String = "StatusTipCell"
class HomeViewController: RootViewController {
    //MARK:- 视图生命周期
    override func viewDidLoad() {
        
        setUpRefreshControl()
        
        super.viewDidLoad()
        
        tableView?.registerClass(statusCell.self, forCellReuseIdentifier: statusID)
        tableView?.registerClass(statusCell.self, forCellReuseIdentifier: tipID)
        visitorView?.setUpInfo("关注一些人，回这里看看有什么惊喜")
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "networkChange", name: AFNetworkingReachabilityDidChangeNotification, object: nil)
    }
    
    @objc func networkChange() {
        
//        AFNetworkActivityIndicatorManager
        self.tableView?.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Automatic)
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(
            self,
            name: AFNetworkingReachabilityDidChangeNotification,
            object: nil)    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func loadData() {
        
        let isPullUp = refreshControl?.isPullupRefresh ?? false
        
        refreshControl?.beginRefreshing()
 
        //获取数据数组中的第一条数据的id
        let since_id = isPullUp ? 0 : (statusList.first?.id ?? 0)
        //获取数据数组中的最后一条数据的id
        let max_id = !isPullUp ? 0 : (statusList.last?.id ?? 0)
        NetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (result) -> () in
            
            self.refreshControl?.endRefreshing()
            guard let result = result?["statuses"] as? [[String:AnyObject]] else{
                return
            }
            
            var arrM = [Status]()
            for dict in result {
                //字典转模型
                let status = Status.yy_modelWithJSON(dict)
                arrM.append(status!)
            }
            print("本次刷新数据条数 \(arrM.count)")
            if since_id > 0 {
                
                self.statusList = arrM + self.statusList
                
            }else {
                self.statusList += arrM
            }
            
            self.tableView?.reloadData()
            
        }
        
        //        let index = 100
        //
        //        let isPullUp = pullUpView.isAnimating()
        //
        //        if !isPullUp {
        //        refreshControl.beginRefreshing()
        //        }
        //        let startIdx = dataList.first ?? index
        //        let lastIdx = dataList.last ?? 0
        //        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
        //            NSThread.sleepForTimeInterval(1.5)
        //            var arrM = [Int]()
        //            if !isPullUp{
        //            for i in (0..<10).reverse() {
        //                arrM.append(i + (startIdx + 1))
        //            }
        //                //如果将这句话放在for循环中,那么会加载3倍的数据
        //                self.dataList = arrM + self.dataList
        //            }else{
        //                for i in 0..<9 {
        //                    arrM.append(lastIdx - 1 - i)
        //                }
        //                self.dataList = self.dataList + arrM
        //            }
        //
        //
        //            dispatch_async(dispatch_get_main_queue()) { () -> Void in
        //
        //
        //                self.refreshControl.endRefreshing()
        //                self.pullUpView.stopAnimating()
        //                self.tableView?.reloadData()
        //            }
        //        }
        //
        //
    }
    //MARK:- 私有属性
    lazy var statusList = [Status]()
}
//MARK:- UITableViewDataSource
extension HomeViewController{
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            
            return NetworkTools.sharedTools.reachable ? 0 : 1
        }
        return statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            return tableView.dequeueReusableCellWithIdentifier(tipID, forIndexPath: indexPath)
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statusID, forIndexPath: indexPath)
        
        let status = statusList[indexPath.row]
        
        cell.textLabel?.text = status.text
        
        return cell
    }
}
